<template>
  <div class="app-container">
    <div style="padding: 5px 0px">
      <toolbar
        :buttons="['submit', 'back']"
        @submit="handleSaved"
        @refresh="handleRefresh"
        @back="handleBack"
      >
      </toolbar>
    </div>
    <div style="padding: 5px 0px">
      <div>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>基础信息</span>
          </div>
          <div class="text item">
            <el-form
              :model="client"
              :rules="rules"
              ref="baseForm"
              label-width="80px"
              style="width: 70%"
              labelPosition="top"
              :inline="true"
            >
              <el-form-item :label="$t('common.name')" prop="name">
                <el-input v-model="client.name"></el-input>
              </el-form-item>
              <el-form-item :label="'显示名称'" prop="displayName">
                <el-input v-model="client.displayName"></el-input>
              </el-form-item>
              <el-form-item :label="'密钥'" prop="secret" v-show="false">
                <el-input v-model="client.secret"></el-input>
              </el-form-item>
              <el-form-item :label="'client类型'" prop="type">
                <type-select v-model="client.type"></type-select>
              </el-form-item>
              <el-form-item :label="'授权同意类型'" prop="consentType">
                <consent-type-select
                  v-model="client.consentType"
                ></consent-type-select>
              </el-form-item>
              <el-form-item :label="'域名'" prop="clientUri">
                <el-input v-model="client.clientUri"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
      <div style="padding-top: 10px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>授权</span>
          </div>
          <div class="text item">
            <el-tabs v-model="permissionTabActiveName">
              <el-tab-pane label="Endpoint" name="endpoint">
                <div>
                  <el-checkbox
                    v-for="(
                      permissionItem, index
                    ) in defaultEndpointPermissions"
                    :key="index"
                    :label="permissionItem.name"
                    v-model="permissionItem.checked"
                  ></el-checkbox>
                </div>
              </el-tab-pane>
              <el-tab-pane label="Grant type" name="grantType">
                <div>
                  <el-checkbox
                    v-for="(
                      permissionItem, index
                    ) in defaultGrantTypePermissions"
                    :key="index"
                    :label="permissionItem.name"
                    v-model="permissionItem.checked"
                  ></el-checkbox>
                </div>
              </el-tab-pane>
              <el-tab-pane label="Scope" name="scope"
                ><div>
                  <el-checkbox
                    v-for="(permissionItem, index) in defaultScopePermissions"
                    :key="index"
                    :label="permissionItem.name"
                    v-model="permissionItem.checked"
                  ></el-checkbox></div
              ></el-tab-pane>
              <el-tab-pane label="Response type" name="responseType"
                ><div>
                  <el-checkbox
                    v-for="(
                      permissionItem, index
                    ) in defaultResponseTypePermissions"
                    :key="index"
                    :label="permissionItem.name"
                    v-model="permissionItem.checked"
                  ></el-checkbox></div
              ></el-tab-pane>
            </el-tabs>
          </div>
        </el-card>
      </div>
      <div style="padding-top: 10px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="padding-right: 10px">登录回调</span>
            <el-button
              class="el-icon-plus"
              type="primary"
              @click="() => handleAddUri(client.redirectUris)"
              >新增</el-button
            >
          </div>
          <div class="text item">
            <div v-for="(item, index) in client.redirectUris" :key="index">
              <el-input
                v-model="client.redirectUris[index]"
                style="width: 400px"
              ></el-input
              ><el-button
                class="el-icon-minus"
                circle
                @click="
                  () =>
                    handleRemoveUri(
                      client.redirectUris,
                      client.redirectUris[index]
                    )
                "
              ></el-button>
            </div>
          </div>
        </el-card>
      </div>
      <div style="padding-top: 10px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="padding-right: 10px">退出回调</span
            ><el-button
              class="el-icon-plus"
              type="primary"
              @click="() => handleAddUri(client.postLogoutRedirectUris)"
              >新增</el-button
            >
          </div>
          <div class="text item">
            <div
              v-for="(item, index) in client.postLogoutRedirectUris"
              :key="index"
              style="padding: 10px 0"
            >
              <el-input
                v-model="client.postLogoutRedirectUris[index]"
                style="width: 400px"
              ></el-input
              ><el-button
                class="el-icon-minus"
                circle
                @click="
                  () =>
                    handleRemoveUri(
                      client.postLogoutRedirectUris,
                      client.postLogoutRedirectUris[index]
                    )
                "
              ></el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getDefaultPermissions,
  getClient,
  addClient,
  updateClient,
} from "@/api/identity";
import typeSelect from "@/components/Select/clientTypeSelect.vue";
import consentTypeSelect from "@/components/Select/clientConsentTypeSelect.vue";
import grantTypeSelect from "@/components/Select/clientGrantTypeSelect.vue";
import toolbar from "@/components/Bar/toolbar.vue";
export default {
  components: { typeSelect, grantTypeSelect, toolbar, consentTypeSelect },
  data() {
    return {
      client: {
        name: null,
        displayName: null,
        type: null,
        consentType: null,
        grantTypes: [],
        permissions: [],
        clientUri: null,
        redirectUris: [],
        postLogoutRedirectUris: [],
      },
      rules: {
        name: [
          {
            required: true,

            message: this.$t("tips.requireItem"),
            trigger: "blur",
          },
        ],
        displayName: [
          {
            required: true,
            message: this.$t("tips.requireItem"),
            trigger: "blur",
          },
        ],
        resources: [
          {
            required: true,
            message: this.$t("tips.requireItem"),
            trigger: "blur",
          },
        ],
      },
      permissionTabActiveName: "endpoint",
      defaultEndpointPermissions: [],
      defaultGrantTypePermissions: [],
      defaultScopePermissions: [],
      defaultResponseTypePermissions: [],
    };
  },
  methods: {
    getData() {
      if (!this.clientId) return;
      getClient(this.clientId).then((res) => {
        if (!res) return;

        this.client = res;

        this.setPermissionItemValue();
      });
    },
    handleSaved() {
      this.$refs["baseForm"].validate((valid) => {
        if (valid) {
          this.saveData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    saveData() {
      this.client.permissions = this.getModifyClientPermissions();
      this.client.grantTypes = this.getDefaultPermssionCheckValue(
        "gt:",
        this.defaultGrantTypePermissions
      );
      this.client.scopes = this.getDefaultPermssionCheckValue(
        "scp:",
        this.defaultScopePermissions
      );
      if (!this.clientId) {
        addClient(this.client).then((res) => {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            position: "bottom-right",
          });
          this.$emit("success", res);
        });
      } else {
        updateClient(this.client).then((res) => {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            position: "bottom-right",
          });
          this.$emit("success", res);
        });
      }
    },
    handleCancel() {
      this.$emit("close");
    },
    getDefaultPermissions(callback) {
      getDefaultPermissions().then((res) => {
        res = res || [];

        res.forEach((element) => {
          element.checked = false;
        });

        this.defaultEndpointPermissions = res.filter((x) => {
          return x.type == 1;
        });

        this.defaultGrantTypePermissions = res.filter((x) => {
          return x.type == 2;
        });

        this.defaultScopePermissions = res.filter((x) => {
          return x.type == 3;
        });

        this.defaultResponseTypePermissions = res.filter((x) => {
          return x.type == 4;
        });

        if (callback) callback();
      });
    },
    handleBack() {
      this.$router.push({ name: "Client" });
    },
    handleRefresh() {
      this.getData();
    },
    setPermissionItemValue() {
      if (!this.client || !this.client.permissions) return;

      this.setDefaultPermssionCheck("ept:", this.defaultEndpointPermissions);
      this.setDefaultPermssionCheck("gt:", this.defaultGrantTypePermissions);
      this.setDefaultPermssionCheck("scp:", this.defaultScopePermissions);
      this.setDefaultPermssionCheck(
        "rst:",
        this.defaultResponseTypePermissions
      );
    },
    getClientPermissions(key) {
      let matchClientPermissions = this.client.permissions.filter(
        (permission) => {
          return permission.indexOf(key) > -1;
        }
      );

      return matchClientPermissions;
    },
    setDefaultPermssionCheck(key, defaultPermissions) {
      if (!defaultPermissions || defaultPermissions.length == 0) return;

      let clientPermissions = this.getClientPermissions(key);

      if (!clientPermissions || clientPermissions.length == 0) return;

      for (let i = 0; i < defaultPermissions.length; i++) {
        let defaultPermission = defaultPermissions[i];
        let matchClientPermission = clientPermissions.find((permission) => {
          return permission == defaultPermission.value;
        });

        if (matchClientPermission) defaultPermission.checked = true;
      }
    },
    getDefaultPermssionCheckValue(key, defaultPermissions) {
      if (!defaultPermissions || defaultPermissions.length == 0) return;

      let clientPermissions = this.getClientPermissions(key);

      return clientPermissions || [];
    },
    handleAddUri(uris) {
      uris = uris || [];
      uris.push("");
    },
    handleRemoveUri(uris, value) {
      if (!uris) return;

      let index = uris.indexOf(value);

      if (index > -1) uris.splice(index, 1);
    },
    getModifyClientPermissions() {
      let result = [];
      let mathEndpointPermissions = this.defaultEndpointPermissions.filter(
        (x) => {
          return x.checked === true;
        }
      );
      if (mathEndpointPermissions && mathEndpointPermissions.length > 0) {
        mathEndpointPermissions.forEach((permission) => {
          result.push(permission.value);
        });
      }

      let mathGrantTypePermissions = this.defaultGrantTypePermissions.filter(
        (x) => {
          return x.checked === true;
        }
      );
      if (mathGrantTypePermissions && mathGrantTypePermissions.length > 0) {
        mathGrantTypePermissions.forEach((permission) => {
          result.push(permission.value);
        });
      }

      let mathScopePermissions = this.defaultScopePermissions.filter((x) => {
        return x.checked === true;
      });
      if (mathScopePermissions && mathScopePermissions.length > 0) {
        mathScopePermissions.forEach((permission) => {
          result.push(permission.value);
        });
      }

      let mathResponseTypePermissions =
        this.defaultResponseTypePermissions.filter((x) => {
          return x.checked === true;
        });
      if (
        mathResponseTypePermissions &&
        mathResponseTypePermissions.length > 0
      ) {
        mathResponseTypePermissions.forEach((permission) => {
          result.push(permission.value);
        });
      }
      return result;
    },
  },
  mounted() {
    this.getDefaultPermissions(() => {
      this.getData();
    });
  },
  computed: {
    clientId() {
      return this.$route.query.clientId;
    },
  },
  watch: {
    permissionTabActiveName: {
      handler(value) {},
    },
  },
  props: {},
};
</script>
<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
